package com.james.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: Oauth2FeignInterceptor
 * @Author: JamesWang
 * @Date: 2021/4/21 22:11
 * @Description: 这个方法就是拦截后的方法
 * 每次的远程调用都进行拦截
 * 主要帮我们做token的传递
 * 因为每个资源服务器都需要token
 * 1.浏览器携带token做远程调用
 * 2.应用本身自发的请求
 * 3.支付宝回调你 你在支付宝回到的方法里面需要远程调用
 * @Version:1.0
 */
@Configuration
public class Oauth2FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        // 怎么拿到之前的token呢?
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!ObjectUtils.isEmpty(requestAttributes)) {
            // 说明是有请求的
            // 这个request之前的request 这个里面有token
            HttpServletRequest request = requestAttributes.getRequest();
            // 拿到token bearer
            String authorization = request.getHeader("Authorization");
            if (StringUtils.hasText(authorization)) {
                // 传递到下一个request对象里面去
                template.header("Authorization",authorization);
                return;
            }
        }
        // 设置一个永久token
        template.header("Authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJyZWFkIl0sImV4cCI6Mzc2NjU4NDE2NiwianRpIjoiM2M5ZGI4ZDUtYzExZi00YWVmLWI4ZTMtYmNlM2UyNjUwNjdmIiwiY2xpZW50X2lkIjoiY2xpZW50In0.iMrh_9gXncws-XVEsVGIr7JRrFrCv83FQgSpvhrwUp27lyh96JUy3mSoXMMtBrPdTRkNSknhrf9kjrTd6F9CBE5hihwCiWy5h6ti6Meu1xaoXJG9WRWOcUgE9jTzHfZgWB8Mq5EwQv9NYOxqdCnwxb4DYu4wUMEqJuLMdNiph8Y0w8pSMUVkaCOSr1n173QSgQCMPPNEbqeD-nzG7YvvwTu-1Ny8_S-xTe2DYl2R88b8mOAAIe3hXI8P0tGi4kIozrlnYD_Ma6FiZ6JfV5ta9gr621KRvoRPOI9vH5j0dSwi8FFx8SDrnuNMfZDMcNy6KfNe9X8e7y3G095bE1hrcQ");
    }
}
